//###############
//FILE : NameServerConnection.java
//WRITER : Daniel Lowengrub, daniel_i_l, 320687098
//EXERCISE : oop ex3 2011
//DESCRIPTION:
//See below
//###############
package oop.ex3.filemanager;


import oop.ex3.communication.ConnectionManager;
import oop.ex3.communication.SocketAddress;
import oop.ex3.protocol.sessions.FileToNameSession;
import oop.ex3.protocol.sessions.Session;

/**
 * This is a connection manager that supports extra functionality that
 * applies to connections between a file manager and a name server.
 * @author daniel
 */
public class NameServerConnection extends ConnectionManager {
    private FileDatabase _fileDatabase;
    private NameServerDatabase _nameServers;
    private SocketAddress _address;
    
    /**
     * Create a connection with the specified file database, nameserver database and
     * socket. The databases are used to initialize a FileToNameSession with the
     * relevant information. The socket address is the address of the 
     * name server we want to connect to.
     * @param fileDb The file database.
     * @param nameDb The name database.
     * @param address The socket address.
     */
    public NameServerConnection (FileDatabase fileDb, NameServerDatabase nameDb,
            SocketAddress address) {
        _address = address;
        _fileDatabase = fileDb;
        _nameServers = nameDb;
    }

    
    /**
     * Initialize a FileToNameSession with using the databases given in the constructor.
     * @param session The FileToNameSession to initialize.
     */
    public void initializeSession(FileToNameSession session) {
        session.setNameServers(_nameServers.getAddressList());
        session.setFileNames(_fileDatabase.getSortedFileNames());
        session.setFileManager(_address);
    }

    /**
     * Execute a session using the streams that were created in the initializeStreams
     * method. Return the exit state of the session.
     * @param session The session to execute.
     * @return The exit status of the session (success / failure)
     */
    public boolean executeSession(Session session) {
        return session.executeSession(getInputStream(), getOutputStream());
    }
    
    /**
     * Get the nameserver database.
     * @return The nameserver database.
     */
    public NameServerDatabase getNameServerDatabase() {
        return _nameServers;
    }

    /**
     * Get the file database.
     * @return The file database.
     */
    public FileDatabase getFileDatabase() {
        return _fileDatabase;
    }
    
}
